package com.zzgele.qmzb.api.web;

import com.zzgele.qmzb.api.core.Constants;
import com.zzgele.qmzb.api.core.Result;
import org.apache.commons.io.IOUtils;
import org.netease.im.CheckSumBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * Created by Martin on 2017-07-21.
 */
@RestController
@RequestMapping(value = {"/route"})
public class RouteController {
    public static final Logger logger = LoggerFactory.getLogger(RouteController.class);
    // 需要改成自身应用的appSecret
    @PostMapping("/nim.action")
    public Result mockClient(HttpServletRequest request) {
        try {
            // 获取请求体
            byte[] body = readBody(request);
            if (body == null) {
                logger.warn("request wrong, empty body!");
                return new Result().setCode(414);
            }
            // 获取部分request header，并打印
            String ContentType = request.getContentType();
            String AppKey = request.getHeader("AppKey");
            String CurTime = request.getHeader("CurTime");
            String MD5 = request.getHeader("MD5");
            String CheckSum = request.getHeader("CheckSum");
            logger.info("request headers: ContentType = {}, AppKey = {}, CurTime = {}, " +
                    "MD5 = {}, CheckSum = {}", ContentType, AppKey, CurTime, MD5, CheckSum);
            // 将请求体转成String格式，并打印
            String requestBody = new String(body, "utf-8");
            logger.info("request body = {}", requestBody);
            // 获取计算过的md5及checkSum
            String verifyMD5 = CheckSumBuilder.getMD5(requestBody);
            String verifyChecksum = CheckSumBuilder.getCheckSum(Constants.NETEASE_SECRET, verifyMD5, CurTime);
            logger.info("verifyMD5 = {}, verifyChecksum = {}", verifyMD5, verifyChecksum);
            if( !CheckSum.equals(verifyChecksum) ) {
                return new Result().setCode(414);
            }
            // TODO: 后续业务处理
            return new Result().setCode(200);
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            return new Result().setCode(414);
        }
    }
    private byte[] readBody(HttpServletRequest request) throws IOException {
        if (request.getContentLength() > 0) {
            byte[] body = new byte[request.getContentLength()];
            IOUtils.readFully(request.getInputStream(), body);
            return body;
        } else {
            return null;
        }
    }
}
